/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package klassetvserver;

import java.net.*;
import java.io.*;
import listenerthread.ServerListenerThread;

public class ServerListener {

    private ServerSocket server;
    public static ServerListenerThread[] clientArray; //Array that contains all the clients
    public static ServerListenerThread[] clientLobbyArray; //Array that contains all the clients in the lobby
    private final int SERVERPORT = 8069;
    private final int MAXPLAYERS = 256;

    public ServerListener() {
        clientArray = new ServerListenerThread[MAXPLAYERS];
        clientLobbyArray = new ServerListenerThread[MAXPLAYERS];
        try {
            server = new ServerSocket(SERVERPORT);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + SERVERPORT);
            System.exit(-1);
        }

        run();
    }

    private void run() {
        int clientIdCounter = 0;
        System.out.println("-KLASSETV SERVER RUNNING-");
        while (true) {
            ServerListenerThread w = null;
            try {
                Socket clientSocket = server.accept();
                //get the next clientArray ID
                for (int i = 0; i < clientArray.length; i++) {
                    if (clientArray[i] == null) {
                        clientIdCounter = i;
                        break;
                    }
                }

                w = new ServerListenerThread(clientSocket, clientIdCounter);
                //add the new clientThread to the clientArray at the clientIdCounter position
                clientArray[clientIdCounter] = w;
                clientLobbyArray[clientIdCounter] = w;

                //start the ServerListenerThreadIn in a Thread
                Thread t = new Thread(clientArray[clientIdCounter]);
                t.start();
            } catch (IOException e) {
                System.out.println("Accept failed: 8069");
                System.exit(-1);
            }
        }

    }
}
